package net.zigin.nhi.waste.view.depotin;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gyf.immersionbar.ImmersionBar;
import com.siberiadante.titlelayoutlib.TitleBarLayout;
import com.yzq.zxinglibrary.android.CaptureActivity;

import net.zigin.nhi.waste.MainApplication;
import net.zigin.nhi.waste.R;
import net.zigin.nhi.waste.constants.Constants;
import net.zigin.nhi.waste.net.ApiCall;
import net.zigin.nhi.waste.net.BaseResponse;
import net.zigin.nhi.waste.net.HttpRetrofitClient;
import net.zigin.nhi.waste.net.PublicService;
import net.zigin.nhi.waste.scan.CodeListener;
import net.zigin.nhi.waste.scan.CodeReceiver;
import net.zigin.nhi.waste.utils.StringUtil;
import net.zigin.nhi.waste.view.depotout.ScanBoxOutActivity;
import net.zigin.nhi.waste.view.depotout.ScanOutActivity;
import net.zigin.nhi.waste.view.widget.DialogManager;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.paperdb.Paper;
import io.reactivex.Observable;

/**
 * 扫医废码界面
 */
public class ScanWasteActivity extends AppCompatActivity implements CodeListener {

    private CodeReceiver receiver;
    private LinearLayout mScan;
    private TitleBarLayout mTitle;
    private TextView mText;

    private Intent resIntent;
    private List<String> wasteIdList;

    private String bind;
    private String scan_out;

    private List<String> wasteBaseIDs = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_waste);

        initView();
        initReceiver();
    }

    private void initView() {
        ImmersionBar.with(this).init();
        mScan = findViewById(R.id.scan);
        mTitle = findViewById(R.id.title);
        mText = findViewById(R.id.text);
    }

    private void initReceiver() {
        receiver = new CodeReceiver();
        receiver.setListener(this);
        registerReceiver(receiver, new IntentFilter("com.barcode.sendBroadcast"));
    }

    @Override
    protected void onResume() {
        super.onResume();

        resIntent = getIntent();
        bind = resIntent.getStringExtra("bind");
        scan_out = resIntent.getStringExtra("scan_out");

        if (StringUtil.isNotEmpty(bind)) {
            if (bind.equals("bind")) {
                mTitle.setTitle("扫码绑定");
                mText.setText("请扫医废二维码");
            } else {
                mTitle.setTitle("扫码入库");
                mText.setText("请扫医废二维码");
            }
        } else {
            if (StringUtil.isNotEmpty(scan_out)) {
                if (scan_out.equals("scan_out")) {
                    mTitle.setTitle("扫码出库");
                    mText.setText("请扫医废/医废箱二维码");
                } else if (scan_out.equals("continue_scan_out")) {
                    mTitle.setTitle("扫码出库");
                    mText.setText("请扫医废二维码");
                } else {
                    mTitle.setTitle("扫码入库");
                    mText.setText("请扫医废二维码");
                }
            } else {
                mTitle.setTitle("扫码入库");
                mText.setText("请扫医废二维码");
            }
        }

        mScan.setOnClickListener(v -> {
            if (MainApplication.scanManager != null) {
                //开启扫描
                Intent intent = new Intent();
                intent.setAction("com.barcode.sendBroadcastScan");
                sendBroadcast(intent);
            } else {
                Intent intent = new Intent(ScanWasteActivity.this, CaptureActivity.class);
                startActivityForResult(intent, 1003);
            }
        });
    }

    /**
     * 界面跳转
     * @param data
     */
    private void jump(String data) {
        if (StringUtil.isNotEmpty(data)) {
            //“继续扫描”的临时存在本地的医废id列表
            Bundle bundle = resIntent.getBundleExtra("BUNDLE");
            if (bundle != null) {
                wasteIdList = (List<String>) bundle.getSerializable("IDLIST");
            }

            Map<String, Object> typeMap = new HashMap<>();
            typeMap.put("content", data);
            Observable<BaseResponse<String>> observable = HttpRetrofitClient.getInstance().create(PublicService.class)
                    .getQrCodeType(Paper.book().read(Constants.TOKEN), typeMap);
            DialogManager.getInstance().showLoading(this);
            HttpRetrofitClient.execute(observable, new ApiCall<String>() {
                @Override
                protected void success(String type) {
                    if (StringUtil.isNotEmpty(type)) {
                        Log.i("扫码类型", type);
                        if ("wasteBox".equals(type)) {
                            if (scan_out.equals("scan_out")) {
                                Paper.book().write(Constants.BOX_CODE, data);
                                Intent intent = new Intent(ScanWasteActivity.this, ScanBoxOutActivity.class);

                                if (wasteIdList != null && wasteIdList.size() > 0) {
                                    Bundle bundle = new Bundle();
                                    bundle.putSerializable("wasteIdList", (Serializable) wasteIdList);
                                    intent.putExtra("BUNDLES", bundle);
                                }
                                startActivity(intent);
                                finish();
                            } else {
                                Toast.makeText(ScanWasteActivity.this, "请扫医废码！", Toast.LENGTH_SHORT).show();
                            }
                        } else if ("wasteBase".equals(type)) {
                            if (resIntent != null) {
                                if (StringUtil.isNotEmpty(bind)) {
                                    if (bind.equals("bind")) {
                                        getWasteDetail(data);
                                    } else {
                                        getScanInWasteDetail(data);
                                    }
                                } else {
                                    if (StringUtil.isNotEmpty(scan_out)) {
                                        if (scan_out.equals("scan_out") || scan_out.equals("continue_scan_out")) {
                                            Paper.book().write(Constants.WASTE_CODE, data);
                                            Intent intent = new Intent(ScanWasteActivity.this, ScanOutActivity.class);

                                            if (wasteIdList != null && wasteIdList.size() > 0) {
                                                Bundle bundle = new Bundle();
                                                bundle.putSerializable("wasteIdList_scan", (Serializable) wasteIdList);
                                                intent.putExtra("BUNDLESCAN", bundle);
                                            }

                                            startActivity(intent);
                                            finish();
                                        } else {
                                            getScanInWasteDetail(data);
                                        }
                                    } else {
                                        getScanInWasteDetail(data);
                                    }
                                }
                            } else {
                                mTitle.setTitle("扫码入库");
                                mText.setText("请扫医废二维码");
                                getScanInWasteDetail(data);
                            }
                        }
                    }
                }
            });
        }
    }

    /**
     * 获取扫码的医废详情
     */
    private void getWasteDetail(String qrCode) {
        wasteBaseIDs.clear();
        String collectUserQrCode = Paper.book().read(Constants.COLLECTOR_CODE);
        if (collectUserQrCode != null && qrCode != null) {
            Map<String, Object> map = new HashMap<>();
            map.put("collectUserQrCode", collectUserQrCode);
            map.put("wasteQrCode", qrCode);
            Observable<BaseResponse<String>> observable = HttpRetrofitClient.getInstance().create(PublicService.class)
                    .getSingleInStorageInfo(Paper.book().read(Constants.TOKEN), map);
            HttpRetrofitClient.execute(observable, new ApiCall<String>() {
                @SuppressLint("DefaultLocale")
                @Override
                protected void success(String data) {
                    Log.i("医废详情", data);
                    JSONObject object = JSON.parseObject(data);
                    String status = object.getString("status");
                    if ("do_collect".equals(status)) {
                        String boxBindWasteType = Paper.book().read(Constants.BOX_BIND_WASTE_TYPE);
                        String wasteClassifyCode = object.getString("wasteClassifyCode");
                        if (StringUtil.isNotEmpty(boxBindWasteType)) {
                            if (boxBindWasteType.equals(wasteClassifyCode)) {
                                String wasteID = object.getString("id");
                                if (wasteID != null) {
                                    wasteBaseIDs.add(wasteID);
                                    getBoxID();
                                }
                            } else {
                                Toast.makeText(ScanWasteActivity.this, "请绑定与箱袋中相同类型的医废！", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            String wasteID = object.getString("id");
                            if (wasteID != null) {
                                wasteBaseIDs.add(wasteID);
                                getBoxID();
                            }
                        }
                    } else {
                        Toast.makeText(ScanWasteActivity.this, "请绑定待入库的医废！", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    }

    /**
     * 扫码入库判断扫的医废码状态
     * @param qrCode
     */
    private void getScanInWasteDetail(String qrCode) {
        wasteBaseIDs.clear();
        String collectUserQrCode = Paper.book().read(Constants.COLLECTOR_CODE);
        if (collectUserQrCode != null && qrCode != null) {
            Map<String, Object> map = new HashMap<>();
            map.put("collectUserQrCode", collectUserQrCode);
            map.put("wasteQrCode", qrCode);
            Observable<BaseResponse<String>> observable = HttpRetrofitClient.getInstance().create(PublicService.class)
                    .getSingleInStorageInfo(Paper.book().read(Constants.TOKEN), map);
            HttpRetrofitClient.execute(observable, new ApiCall<String>() {
                @SuppressLint("DefaultLocale")
                @Override
                protected void success(String data) {
                    Log.i("医废详情", data);
                    JSONObject object = JSON.parseObject(data);
                    String status = object.getString("status");
                    //判断医废状态，仅待入库的医废可入库
                    if ("do_collect".equals(status)) {
                        Paper.book().write(Constants.WASTE_CODE, qrCode);
                        Intent intent = new Intent(ScanWasteActivity.this, ScanInActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        Toast.makeText(ScanWasteActivity.this, "请扫待入库的医废码！", Toast.LENGTH_SHORT).show();
                    }

                }
            });
        }
    }

    /**
     * 绑定并获取箱的ID.目的是覆盖boxID，回到箱袋绑定界面时用最新的boxID获取信息
     */
    private void getBoxID() {
        String qrCode = Paper.book().read(Constants.BOX_CODE);
        Map<String, Object> map = new HashMap<>();
        map.put("wasteBoxQrCode", qrCode);
        map.put("wasteBaseIds", wasteBaseIDs);
        Observable<BaseResponse<String>> observable = HttpRetrofitClient.getInstance().create(PublicService.class)
                .bindBagWithBox(Paper.book().read(Constants.TOKEN), map);
        HttpRetrofitClient.execute(observable, new ApiCall<String>() {
            @Override
            protected void success(String data) {
                Log.i("箱袋绑定", data);
                Paper.book().write(Constants.BOX_ID, data);
                Intent intent = new Intent(ScanWasteActivity.this, BoxBindActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }

    @Override
    public void getData(String data) {
        Log.i("扫码结果", data);
        jump(data);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描二维码/条码回传
        if (requestCode == 1003 && resultCode == RESULT_OK) {
            if (data != null) {
                //返回的文本内容
                String content = data.getStringExtra("codedContent");
                Log.i("扫码结果：", content);
                jump(content);
            }
        }
    }

    @Override
    protected void onDestroy() {
        if (receiver != null) {
            unregisterReceiver(receiver);
            receiver = null;
            System.gc();
        }
        super.onDestroy();
    }
}